
const Controller = require('egg').Controller

class FlowsController extends Controller {
  constructor(ctx) {
    super(ctx)

    this.createRule = {
      name: { type: 'string', required: true, allowEmpty: false },
      access: { type: 'string', required: true, allowEmpty: false }
    }
  }
  
  // 获取所有角色(分页/模糊)
  async index() {
    const { ctx, service } = this
    const payload = ctx.query
    const res = await service.flows.index(payload)
    ctx.helper.success({ctx, res})
  }

  // 获取所有角色(分页/模糊)
  async echarts() {
    const { ctx, service } = this
    const payload = ctx.query

    const res = await service.flows.echarts(payload)
    ctx.helper.success({ctx, res})
  }

  // 新增之前调用(默认值，不一定需要)
  async new() {
    const { ctx, service } = this
    const payload = ctx.query
    const res = await service.flows.new(payload)
    ctx.helper.success({ctx, res})
  }

  // 获取单个角色
  async show() {
    const { ctx, service } = this
    const { id } = ctx.params
    const res = await service.flows.show(id)
    ctx.helper.success({ctx, res})
  }

  // 编辑之前调用 根据具体业务修改代码 默认和show相同
  async edit() {
    await this.show()
  }

  // 创建角色
  async create() {
    const { ctx, service } = this
    ctx.validate(this.createRule)
    const payload = ctx.request.body || {}
    const res = await service.flows.create(payload)
    ctx.helper.success({ctx, res})
  }

  // 修改角色
  async update() {
    const { ctx, service } = this
    ctx.validate(this.createRule)
    const { id } = ctx.params
    const payload = ctx.request.body || {}
    await service.flows.update(id, payload)
    ctx.helper.success({ctx})
  }
  
  // 删除单个角色
  async destroy() {
    const { ctx, service } = this
    const { id } = ctx.params
    await service.flows.destroy(id)
    ctx.helper.success({ctx})
  }

  // 获取所有角色(分页/模糊)
  async mine() {
    const { ctx, service } = this

    const _id = ctx.state.user.data._id
    const payload = ctx.query

    // 调用 Service 进行业务处理
    const res = await service.flows.index(payload, _id)
    ctx.helper.success({ctx, res})
  }

  async init() {
    const { ctx, service } = this
    const payload = ctx.query
    const { days } = payload
    function sleep(time) {
      return new Promise((resolve) => setTimeout(resolve, time))
    }

    const list = await ctx.model.Devices.find()
    for (const device of list) {
      for (let index = 0; index < days; index++) {
        try {
          await service.flows.getFlows(device, (index * 24) , 24)
        } catch (e) {
          console.log(e.toString())
        }
        await sleep(1000 * 3)
        
      }
      // console.log(device.deviceid)
    }
    ctx.helper.success({ctx, res: 'OK'})
  }
}

module.exports = FlowsController

